package com.example.demo.configuration;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.example.demo.service.UserService;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	UserService userService;
	//暂时设置密码不加密
	@Bean
	public PasswordEncoder passwordEncoder()
	{
		return NoOpPasswordEncoder.getInstance();
	}
	/**
	 * 从数据库配置用户登录权限
	 */
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
		auth.userDetailsService(userService);
	  }
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		.antMatchers("/user/**").hasRole("user")
		.antMatchers("/admin/**").hasRole("admin")
		.antMatchers("/base/**")
		.permitAll()
		.and()
		.formLogin()
		.loginPage("/login")//必须有一个对应的控制器请求路径，用于转向自定义的登陆页面
		.loginProcessingUrl("/logincom")//登录页面的form表单请求路径
		.usernameParameter("utel")
		.passwordParameter("upassword") 
	    .successHandler(new AuthenticationSuccessHandler() {
				  
				  @Override public void onAuthenticationSuccess(HttpServletRequest request,
				  HttpServletResponse response, Authentication authentication) throws
				  IOException, ServletException {
				  
                  //存储用户角色
                  Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
                  //如果是“boss”,则跳转到boss主页面
                  if(roles.contains("ROLE_user")) {
                	  String path = request.getContextPath(); 
                	  String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                	  response.sendRedirect(basePath+"user/userpage");
                  }
                  //如果是“emp”,则跳转到emp主页面
                  if(roles.contains("ROLE_admin")) {
                	  String path = request.getContextPath(); 
                	  String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                	  response.sendRedirect(basePath+"admin/adminpage");
                  }
				  
				  
				  } })
				 
	    .permitAll()
		.and()
		.logout()
		.logoutUrl("/logout")
		.clearAuthentication(true)
		.invalidateHttpSession(true)
		.logoutSuccessHandler(new LogoutSuccessHandler() {
			
			@Override
			public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
					throws IOException, ServletException {
				//退出后重定向到登录页面
				response.sendRedirect("base/mainpage");
				
			}
		})
		.and()
		.csrf()
		.disable();
		
	}
}
